import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MelonLibStoreService {

  constructor() { }

  sotre<E>(name: string, value: E, scope: 'session' | 'local' = 'local'): void {
    if (typeof value === 'string') {
      if (scope === 'local') {
        localStorage.setItem(name, value);
      } else {
        sessionStorage.setItem(name, value);
      }
    } else {
      if (scope === 'local') {
        localStorage.setItem(name, JSON.stringify(value));
      } else {
        sessionStorage.setItem(name, JSON.stringify(value));
      }
    }
  }

  load<E>(name: string, scope: 'session' | 'local' = 'local'): E {
    switch (scope) {
      case 'local': return this.parse(localStorage.getItem(name));
      case 'session': return this.parse(sessionStorage.getItem(name));
      default: return this.parse(localStorage.getItem(name));
    }

  }

  remove(name: string, scope: 'session' | 'local' = 'local'): void {
    switch (scope) {
      case 'local': localStorage.removeItem(name); return;
      case 'session': sessionStorage.removeItem(name); return;
      default: localStorage.removeItem(name); return;
    }
  }

  clear(scope: 'session' | 'local' | 'all' = 'local'): void {
    switch (scope) {
      case 'local': localStorage.clear(); return;
      case 'session': sessionStorage.clear(); return;
      default: localStorage.clear(); sessionStorage.clear(); return;
    }
  }


  private parse(val: string): any {
    try {
      return JSON.parse(val);
    } catch (e) {
      return val;
    }
  }

}
